import asyncio
from warnings import catch_warnings
import requests
import websockets
import json
import base64
import Googletrans
import DB.PDBC as db
import os
from sqlalchemy import text

"""
    分析图片
"""

async def file_to_base64(file_path):

    # 读取文件内容并转换为字节数据
    with open(file_path, "rb") as file:
        file_bytes = file.read()

    # 将字节数据转换为Base64编码的字符串
    base64_encoded_str = base64.b64encode(file_bytes).decode('utf-8')

    return "data:image/jpeg;base64," + base64_encoded_str

async def analyzeImages(file_path,fn_index):
    uri = "http://192.168.31.253:7860/run/predict"  # 替换为你的WebSocket服务器URI
    fileBase64 = await file_to_base64(file_path)
    msg = {"data": [0, "", "", fileBase64, None, None, None, None], "event_data": None, "fn_index": fn_index,
           "session_hash": "zc71mw0mh0q"}
    response = requests.post(uri, json=msg)
    if response.status_code == 200:
        # 处理响应内容
        content = response.json()
        return content
    else:
        print(response)
        return {
            "state":"error"
        }

async def updateDbImg():
    sql = """
        SELECT
          a.GROUP_ID,
          a.GROUP_NUM,
          COALESCE(max(b.IMAGE_INDEX),0) as max
        FROM
          meitu_database a LEFT JOIN
          image_groups b on b.GROUP_ID = a.GROUP_ID 
        where 
          a.IS_DOWNLOAD = 2
        GROUP BY
          a.GROUP_ID,
          a.GROUP_NUM 
        HAVING
          a.GROUP_NUM > max
        order by update_date
        limit 1
    """
    con = db.connect()
    result = con.execute(text(sql)).fetchall()
    for row in result:
        remarkIndex = con.execute(text("select COALESCE(MAX(IMAGE_INDEX) + 1, 1) as remark_index from image_groups where GROUP_ID = :GROUP_ID"),{'GROUP_ID':row[0]}).fetchone()
        for index in range(remarkIndex[0],row[1] + 1):
            imgPath = await getImgPath(row[0],index)
            print(row[0],index,imgPath)
            if os.path.isfile(imgPath) == False:
                print(f"is not file:{imgPath}")
                continue
            response1 = await analyzeImages(imgPath,257)
            print(response1)
            response2 = await analyzeImages(imgPath,256)
            print(response2)
            imgRemark1 = ""
            imgRemark2 = ""
            imgRemark1Cn = ""
            imgRemark2Cn = ""
            try:
                imgRemark1 = response1['data'][0]
                imgRemark2 = response2['data'][0]
                imgRemark1Cn = Googletrans.enToCn(imgRemark1)
                print(imgRemark1Cn)
                imgRemark2Cn = Googletrans.enToCn(imgRemark2)
                print(imgRemark2Cn)
            except Exception as e:
                print(e)
            con.execute(text("insert into image_groups (GROUP_ID,IMAGE_INDEX,REMARK1_EN,REMARK2_EN,REMARK1_CN,REMARK2_CN) values (:GROUP_ID,:IMAGE_INDEX,:REMARK1_EN,:REMARK2_EN,:REMARK1_CN,:REMARK2_CN)"),
                        {"GROUP_ID":row[0],"IMAGE_INDEX":index,"REMARK1_EN":imgRemark1,"REMARK2_EN":imgRemark2,"REMARK1_CN":imgRemark1Cn,"REMARK2_CN":imgRemark2Cn})
            con.commit()


    con.close()



async def getImgPath(groupId,imageIndex):
    """
    根据分组和索引获取一个图片的地址
    """
    sys_path = "G:\\04 buondua"

    # 将输入的数字转换为字符串，以便于提取前缀
    input_str = str(groupId)

    # 提取前缀部分，即输入数字的前几位（在这里是前两位，但可以根据需要调整）
    # 这里使用切片操作[:-2]然后转换为int再*100来获取前缀对应的起始值，
    # 但实际上更简单的方法是直接切片后加'00'再转换为int。
    # 不过为了展示多种方法，这里先用一种稍显复杂的方式。
    # 注意：这种方法假设输入数字至少有两位，如果可能有一位的情况需要额外处理。
    prefix_int = int(input_str[:-2]) * 100  # 提取前两位并转换为对应的百位数

    # 计算范围的下限和上限
    lower_bound = prefix_int
    upper_bound = prefix_int + 99

    # 返回结果，格式化为字符串
    return f"{sys_path}\\{lower_bound} - {upper_bound}\\{groupId}\\{imageIndex}.jpg"

if __name__ == '__main__':


    if '__main__' == __name__:
        while True:
            asyncio.run(updateDbImg())
    else:
        updateDbImg()

        # 运行异步客户端
        response = analyzeImages("C:\\Users\\LiuXi\\Desktop\\img.jpg",256)
        print(response)
        if response['success']:
            imgRemark = response['output']['data'][0]
            print(imgRemark)
            print(Googletrans.enToCn(imgRemark))
        else:
            print(response)